//index.js
import http from '../../utils/http.js'
import { getQueryString } from '../../utils/util'
//获取应用实例
const app = getApp()

Page({
  data: {
    code: "", // 扫描出的code
    mapctx: null, // map context对象
    markers: [],
    markerId: 0,
    markerIdx: 0,
    backImg: 'https://tdjhht.hfbright.cn/static/images/main_background.png', // 背景图片
    latitude: '', // 纬度
    longitude: '', // 经度
    islogin: false,
    userInfoShow: false,
    avatarUrl: "",
    nickname: "",
    bindShow: false,
    shareUserid: "",
    type: "",
    deviceId: "",
    deviceType: "",
    isFirstAuth: true
  },

  onLoad: function (options) {
    let shareUserid = options.userid
    let type = options.type
    if (shareUserid) { // 需要绑定
      this.setData({
        shareUserid,
        type
      })
    }
    // 处理扫码逻辑
    let query = decodeURIComponent(options.q)
    if (query) {
      let deviceId = getQueryString('id', query)
      app.globalData.deviceCode = deviceId;
      this.setData({
        deviceId
      })
    }
    this.judgeLogin()
    // this.locationAuth()
    this.authLogin()
    // wx.hideTabBar({
    //   animation: true
    // })
    this.loadBackImg()
    try {
      wx.getSetting({
        withSubscriptions:true,
        success (res) {
          console.log("订阅消息设置：");
          console.log(res.subscriptionsSetting);
          if(res.subscriptionsSetting&&res.subscriptionsSetting.itemSettings&&res.subscriptionsSetting.itemSettings["22zciaYGgf-qpsapBVTwnjqN4KsklvoVddUaWotZ29Y"]=="accept"){
            console.log("订阅一次消息");
            wx.requestSubscribeMessage({
              tmplIds: ['22zciaYGgf-qpsapBVTwnjqN4KsklvoVddUaWotZ29Y'],
              success (res) { }
            })
          }
        }
      })
    } catch (error) {
      console.log(error);
    }
    
  },
  onShow() {
    // this.data.mapctx = wx.createMapContext("map", this)
    // app.globalData.lastPath = "/pages/index/index"
    this.setData({
      islogin: app.globalData.needLogin ? false : true
    })
  },
  judgeLogin() {
    http.request("/auth/status")
      .then(res => {
        // this.setData({
        //   islogin: res.data.status == 1 ? true : false
        // })
      })
  },
  loadBackImg() {
    http.request("/home/origin")
      .then(res => {
        var originDatas = res.data.originDatas;
        var backImg = "";
        if(originDatas!=null&&originDatas.length>0){
          for(var i=0;i<originDatas.length;i++){
            var origin = originDatas[i];
            if(origin.type=="IMG2"){
              backImg = origin.remote_url;
            }
          }
        }
        if(backImg!=null&&backImg!=""){
          this.setData({
            backImg: backImg
          })
        }
      })
  },
  authLogin() {
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        let params = {
          code: res.code
        }
        http.request("/auth/login", params)
          .then(res => {
            if (this.data.type == 1 && this.data.isFirstAuth) { // 分享
              this.setData({
                bindShow: true,
                isFirstAuth: false
              })
            }
            if (res.data.status == 1) { // 1 注册过 2 未注册  
              app.globalData.needLogin = false
              wx.setStorageSync('token', res.data.token)
              // this.setData({
              //   bindShow: false
              // })
              // 设备二维码跳转判断
              this.codeNavi()
            } else if (res.data.status == 2) {

              if (this.data.deviceId) { // 微信扫设备码
                wx.showToast({
                  title: '请先登录',
                  icon: 'none'
                })
              }
              app.globalData.needLogin = true
              this.setData({
                islogin: app.globalData.needLogin ? false : true
              })
            }
          })
          .catch(res => {

          })
      }
    })
  },
  codeNavi(){
    if (this.data.deviceId) { // 微信扫设备码
      let params = {
        deviceId: this.data.deviceId
      }
      http.request("/machine/qrType",params)
      .then(res=>{
        this.data.deviceType = res.data.type
      
        if (this.data.deviceType == 1) { // 家庭版本
          //pages/addDrinking/addDrinking
          wx.navigateTo({
            url: '/pages/addDrinking/addDrinking?deviceId=' + this.data.deviceId,
          })
        }
        if (this.data.deviceType == 2) { // 渠道版本
          wx.navigateTo({
            url: '/pages/waterDrink/waterDrink?deviceId=' + this.data.deviceId,
          })
        }
      })
    }
  },
  bindGetUserInfo(e) {
    let encryptedData = e.detail.encryptedData
    let signature = e.detail.signature
    let userInfo = e.detail.userInfo
    let rawData = e.detail.rawData
    let nickname = JSON.parse(rawData).nickName
    let avatarUrl = JSON.parse(rawData).avatarUrl
    let iv = e.detail.iv
    let params = {
      encryptedData,
      iv,
      rawData,
      signature
    }
    this.setData({
      userInfoShow: true,
      islogin: true,
      avatarUrl,
      nickname
    })

  },
  locationAuth() {
    wx.authorize({
      scope: 'scope.userLocation',
      success: () => {
        wx.getLocation({
          type: 'gcj02',
          altitude: true,
          isHighAccuracy: true,
          success: (res) => {
            let latitude = res.latitude
            let longitude = res.longitude
            this.setData({
              latitude: latitude,
              longitude: longitude
            })
          },
          fail: () => {

          }
        })
      }
    })
  },
  markertap(e) {
    let markerId = e.markerId
    let markerIdx = 0
    for (let i = 0; i < this.data.markers.length; i++) {
      if (this.data.markers[i].id != markerId) {
        this.data.markers[i].iconPath = "../../imgs/marksIcon.png"
      } else {
        markerIdx = i
        this.data.markers[i].iconPath = "../../imgs/marksIconOn.png"
      }
    }

    this.setData({
      markers: this.data.markers,
      markerId,
      markerIdx
    })
  },
  scan() {
    wx.scanCode({
      onlyFromCamera: true,
      success: (res) => {
        this.data.deviceId = getQueryString('id', res.result)
        this.codeNavi()
        // if (type == 1) { // 家庭版本
        //   //pages/addDrinking/addDrinking
        //   wx.navigateTo({
        //     url: '/pages/addDrinking/addDrinking?deviceId=' + deviceId,
        //   })
        // }
        // if (type == 2) { // 渠道版本
        //   wx.navigateTo({
        //     url: '/pages/waterDrink/waterDrink?deviceId=' + deviceId,
        //   })
        // }

        // if(res.scanType == 'QR_CODE') {// 普通二维码
        //   this.data.code = res.result
        //   wx.navigateTo({
        //     url: '/pages/waterDrink/waterDrink?deviceId=' + this.data.code,
        //   })
        // }else if(res.scanType == "WX_CODE"){  // 小程序码
        //   wx.navigateTo({
        //     url: "/" + res.path
        //   })
        // }
      }
    })
  },
  moveToLocation() {
    this.data.mapctx.moveToLocation({
      longitude: this.data.longitude,
      latitude: this.data.latitude,
      success: () => {

      }
    })
  },
  regionchange() {
    this.data.mapctx.getScale({
      success: (res) => {
        console.log(res)
        let markers = []
        if (res.scale > 13) {
          this.data.mapctx.getRegion({
            success: (res) => {
              let params = {
                nLat: res.northeast.latitude,
                nLng: res.northeast.longitude,
                sLat: res.southwest.latitude,
                sLng: res.southwest.longitude
              }
              http.request("/machine/searchInRegion", params)
                .then(res => {
                  let machines = res.data.machines
                  for (let i = 0; i < machines.length; i++) {
                    markers.push({
                      id: machines[i].id,
                      deviceCode: machines[i].deviceCode,
                      latitude: machines[i].lnt,
                      longitude: machines[i].lng,
                      name: machines[i].addressTitle,
                      iconPath: "../../imgs/marksIconOn.png",
                      width: 31,
                      height: 38,
                      title: machines[i].addressTitle,
                      addr: machines[i].addressDetail
                    })
                  }
                  this.setData({
                    markers
                  })
                })
                .catch(res => {
                  this.setData({
                    markers
                  })
                })
            }
          })
        } else {
          this.setData({
            markers
          })
        }
      }
    })
  },
  getPhoneNumber(e) {
    let params = {
      iv: e.detail.iv,
      encryptedData: e.detail.encryptedData,
      sessionKey: app.globalData.session.sessionKey,
      nickName: this.data.nickname,
      avatarUrl: this.data.avatarUrl,
      unionId: app.globalData.session.unionid ? app.globalData.session.unionid : "",
      openId: app.globalData.session.openid,
      deviceCode: app.globalData.deviceCode,
    }
    this.setData({
      userInfoShow: false
    })
    http.request("/auth/loginWithPhoneNumber", params)
      .then(res => {
        wx.setStorageSync('token', res.data.token)
        app.globalData.needLogin = false
        if (app.globalData.lastPath != "") {
          wx.switchTab({
            url: app.globalData.lastPath,
          })
        }
      })
      .catch(res => {

      })
  },
  onCancel() {
    this.setData({
      userInfoShow: false,
      bindShow: false,
    })
  },
  bindconfirm(e) {
    let encryptedData = e.detail.encryptedData
    let signature = e.detail.signature
    let userInfo = e.detail.userInfo
    let rawData = e.detail.rawData
    let nickname = JSON.parse(rawData).nickName
    let avatarUrl = JSON.parse(rawData).avatarUrl
    if (app.globalData.session.openid) {
      let params = {
        openId: app.globalData.session.openid,
        userId: this.data.shareUserid,
        avatarUrl: avatarUrl
      }
      http.request("/auth/bind", params)
        .then(res => {
          wx.showToast({
            title: "绑定成功",
            icon: "none"
          })
          this.setData({
            bindShow: false
          })
          this.authLogin()
        })
        .catch(res=>{
          this.setData({
            bindShow: false
          })
        })
    } else {
      console.error("等待openid的获取")
    }

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: app.globalData.shareTitle,
      path: '/pages/index/index'
    }
  }
})